<template>
  <div class="app-container">
    <!-- 查询框 -->
    <div class="filter-container">
<!--      <el-input style="width: 200px;" v-model="pageParam.superSearchKeyWord" placeholder="关键字查询..." class="filter-item"-->
<!--        @keyup.enter.native="handleFilter" @input="handleFilter" />-->
<!--      <el-select @change="categoryChange" style="width: 140px;" v-model="pageParam.model.departmentId" class="filter-item" placeholder="科室分类">-->
<!--        <el-option v-for="item in departmentCategoryList" :key="item.id" :label="item.name" :value="item.id" />-->
<!--      </el-select>-->
<!--      <el-select @change="categoryChange" style="width: 140px;" v-model="pageParam.model.isUsed" class="filter-item" placeholder="使用情况">-->
<!--        <el-option key="0" label="空闲" value="0" />-->
<!--        <el-option key="1" label="占用" value="1" />-->
<!--        <el-option key="" label="所有" value="" />-->
<!--      </el-select>-->
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="flushList()">
        刷新病房
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="list" @sort-change="sortChange" fit highlight-current-row style="width: 100%;">
      <!-- 表格字段 -->
      <el-table-column type="index" label="编号">
      </el-table-column>

      <el-table-column prop="name" label="科室">
      </el-table-column>

      <el-table-column prop="telephone" label="电话">
      </el-table-column>

      <el-table-column prop="isUsed" label="使用情况">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status==0" type="success">正常</el-tag>
          <el-tag v-if="scope.row.status==1" type="danger">禁用</el-tag>
        </template>
      </el-table-column>


      <el-table-column label="操作" fit>
        <template slot-scope="{row,$index}">
          <el-button size="small" type="primary" @click="openWin(row,$index)" >详情</el-button>
          <el-popconfirm
            title="确认禁用病床吗？"
            @onConfirm="openWin(row,$index)"
          >
            <el-button slot="reference" v-if="row.status==0" size="small" type="danger">禁用</el-button>

          </el-popconfirm>
          <el-popconfirm
            title="确认启用病床吗？"
            @onConfirm="passOutHospital(row,$index)"
          >
            <el-button slot="reference" v-if="row.status==1" size="small" type="warning" >启用</el-button>

          </el-popconfirm>
        </template>
      </el-table-column>

    </el-table>

    <!-- 分页组件 -->
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize"
      @pagination="getListByPage" />

    <!-- 弹窗组件(病房详情) -->
    <el-dialog title="病房详情" :visible.sync="showRoomDetail">
      <el-form ref="dataForm" :rules="rules" :model="OnePatient" label-position="right" label-width="70px" style="width: 550px; margin-left:120px;">

        <el-row>
          <el-col :span="12"><div class="grid-content bg-purple">
            <el-form-item label="患者姓名">
              <span>{{ OnePatient.patientName }}</span>
            </el-form-item>
            <el-form-item label="护士姓名">
              <span>{{ OnePatient.nurseName }}</span>
            </el-form-item>
            <el-form-item label="科室">
              <span>{{ OnePatient.name }}</span>
            </el-form-item>
          </div></el-col>
          <el-col :span="12"><div class="grid-content bg-purple-light">
            <el-form-item label="联系方式">
              <span>{{ OnePatient.otherPhone }}</span>
            </el-form-item>
            <el-form-item label="医生姓名">
              <span>{{ OnePatient.doctorName }}</span>
            </el-form-item>
            <el-form-item label="床位">
              <span>{{ OnePatient.no }}</span>
            </el-form-item>
          </div></el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="showRoomDetail = false">
          退出
        </el-button>
      </div>
    </el-dialog>


    <!-- 弹窗组件(分配病房与护士) -->
    <el-dialog title="分配病房&护士" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="50px" style="width: 100%; margin-left:80px;">


        <el-row>
          <el-col :span="12"><div class="grid-content bg-purple">
            <span>待床患者：</span>
            <el-select style="width: 140px;"  class="filter-item" v-model="addBedAndNurse.patientId"  placeholder="待床患者">
              <el-option v-for="ttkk of noBedPatientList" :key="ttkk.patientId" :label="ttkk.patientName" :value="ttkk.patientId" />
            </el-select>

          </div></el-col>
          <el-col :span="12"><div class="grid-content bg-purple-light">
            <span>护士：</span>
            <el-select style="width: 140px;"  class="filter-item" v-model="addBedAndNurse.nurseId" placeholder="护士">
              <el-option v-for="item of nurseList" :key="item.id" :label="item.realName" :value="item.id" />
            </el-select>
          </div></el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="addRoomDetailToPatient()">
          分配
        </el-button>
      </div>
    </el-dialog>


    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">确认</el-button>
      </span>
    </el-dialog>

    <!-- 弹窗组件(九) -->
    <el-dialog title="病房列表" :visible.sync="dialogTest" width="30%">

      <el-container>
        <el-header>
          <div style="margin-left: 70px">
            <el-tag type="danger">红色</el-tag>-已满&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <el-tag type="success">绿色</el-tag>-空闲
          </div>
        </el-header>
        <el-main>
          <div id="box">
            <div class="item" v-for="it in roomList">
              <el-button v-if="it.isUsed==1" type="danger" @click="lookOne(it.id)">{{it.no}}</el-button>
              <el-button v-if="it.isUsed==0" type="success" @click="use(it.id,it.departmentId)">{{it.no}}</el-button>
            </div>
          </div>
        </el-main>
      </el-container>

    </el-dialog>

  </div>
</template>

<script>
  import {
    mapGetters,
    mapState
  } from 'vuex'
  //图片黏贴插件
  import '../../assets/js/image-paste.min.js'
  //quill富文本编辑器css
  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'
  import 'quill/dist/quill.bubble.css'
  //quill富文本编辑器 组件倒入
  import {
    quillEditor
  } from 'vue-quill-editor'

  import {
    getToken
  } from '@/utils/auth'

//导入床位处理的方法
  import {
    getDepartmentCategoryList,
    lookPatientByRoomId,
    getNurseList,
    getNoBedPatientList,
    giveBedAndNurse,
    getDepartmentList,
    getRoomListByBox
  } from '@/api/nurse/room'
  //倒入文件上传api
  import {
    uploadImage
  } from '@/api/file'

  //导入组件  记得声明组件
  import Pagination from '@/components/Pagination'

  export default {
    components: { //在这里声明组件
      Pagination,
      quillEditor
    },
    computed: {
      ...mapGetters({
        'userName': 'name',
        'roles': 'roles',
        'storeNickName': 'nickName'
      }),
      editor() {
        return this.$refs.myQuillEditor.quill
      }
    },
    data() {
      return {
        editorOption: {
          modules: {

            imagePaste: {
              addImageBlob: function(blob, callback) {
                var formData = new FormData()

                formData.append('image', blob)

                // console.log(blob, callback)

                // your upload function, get the uploaded image url, add then
                uploadImage(formData).then(res => {
                  console.log(res)
                  // let imageUrl =
                  //   'https://wnbucket.oss-cn-shanghai.aliyuncs.com/15930888655881592094766089.jpg'

                  callback(res.content)
                }).catch(err => {
                  console.log(err)
                })


              }
            }

          }
        },
        dialogImageUrl: '',
        dialogVisible: false,
        headerToken: {
          'Authorization': getToken()
        },
        imageUploadAction: process.env.VUE_APP_BASE_API + '/file/uploadImage',
        list: [], //列表数据
        roomList:[], //病房数据
        total: 0,
        createTimeOrderOptions: [{
            label: '创建时间 升序',
            key: '+create_time',
            value: 'create_time asc'
          },
          {
            label: '创建时间 降序',
            key: 'create_time',
            value: 'create_time desc'
          }
        ],

        listQuery: { //分页 排序  查询参数
          pageNum: 1,
          pageSize: 5
        },
        fieldQuery: { // 按字段查询
          realName: ''
        },
        dialogFormVisible: false,
        showRoomDetail:false,
        dialogTest: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建'
        },
        dialogPvVisible: false,
        pvData: [],
        temp: {
          id: '',
          no:'',
          isUsed: '',
          departmentId:'',
          name: '',
          status: ''
        },
        OnePatient: {
          id:'',
          patientName:'',
          nurseName:'',
          otherPhone:'',
          doctorName:'',
          no:'',
          name:''
        },
        tempImageList: [

        ],
        //待床患者列表
        noBedPatientList:[

        ],
        //护士列表
        nurseList:[

        ],
        addBedAndNurse:{
          patientId:'',
          roomId:'',
          nurseId:'',
          departmentId:''
        },
        departmentCategoryList: [

        ],
        rules: {},
        pageParam: {
          pageNum: 1,
          pageSize: 5,
          model: {

          },
          orderParams: [
            'name desc'
          ],
          superSearchKeyWord: ''
        },
        roleList: []

      }
    },
    created() {
      this.getListByPage()
    },
    methods: {
      sortChange(val) {
        // console.log("排序参数",val)
        let prop = val.prop
        let order = val.order === 'ascending' ? 'asc' : 'desc'
        let orderParam = prop + ' ' + order
        // console.log(orderParam)
        for (let i = 0; i < this.pageParam.orderParams.length; i++) {
          if (this.pageParam.orderParams[i].indexOf(prop) > -1) {
            this.pageParam.orderParams.splice(i, 1)
          }
        }
        this.pageParam.orderParams.push(orderParam)
        console.log(this.pageParam.orderParams)
        this.getListByPage()
      },
      getDepartmentCategoryList() {
        let pageNum = 1
        let pageSize = 1000
        let orderParams = []
        let model = {
          checkStatus: 1 //只查询 已经审核通过的分类
        }
        let pageParam = {
          pageNum,
          pageSize,
          orderParams,
          model
        }

        //查询科室分类
        getDepartmentCategoryList().then(res => {
          // console.log(res)
          // alert(JSON.stringify(res))
          this.departmentCategoryList = res.content
        }).catch(err => {
          console.log(err)
        })
      },
      getTempImageList() {
        //清空文件列表
        this.tempImageList = []

        let tempPageParam = this.pageParam
        tempPageParam.model = {
          productId: this.temp.id
        }
        tempPageParam.pageSize = 1000
        searchSomeProductimageByPage(tempPageParam).then(res => {
          // console.log(res)
          let resList = res.content.list
          let tempImageData = {
            name: '',
            url: '',
            key: ''
          }
          this.$refs.imagesUpload.clearFiles()
          for (let i = 0; i < resList.length; i++) {
            tempImageData.name = resList[i].imageUrl
            tempImageData.url = resList[i].imageUrl
            tempImageData.key = resList[i].imageUrl
            this.tempImageList.push(tempImageData)
          }

        }).catch(err => {
          console.log(err)
        })
      },

      //刷新病房
      flushList(){
        this.pageParam.model = {}
        this.getListByPage()
      },

      //获取病房信息列表
      getListByPage() {
        this.pageParam.pageNum = this.listQuery.pageNum
        this.pageParam.pageSize = this.listQuery.pageSize

        console.log(this.pageParam.orderParams)
        // alert(JSON.stringify(this.pageParam))
        getDepartmentList(this.pageParam).then(res => {
          // console.log(res)
          // alert(JSON.stringify(res))
          //将得到的数据赋值
          this.list = res.content.list
          this.total = res.content.total
        }).catch(err => {
          console.log(err)
        })
      },

      //查看病床详情（患者）
      lookOne(id) {
        this.OnePatient={}
        this.showRoomDetail = true
        let temp = {
          id: id
        }
        lookPatientByRoomId(temp).then(res => {
          //alert(JSON.stringify(res.content));
          this.OnePatient = res.content;
        })
      },

      use(roomId,departmentId){
        this.addBedAndNurse={}
        this.addBedAndNurse.roomId=roomId
        this.addBedAndNurse.departmentId=departmentId
        this.dialogFormVisible = true
        this.getNoBedPatientListFk()
        this.getNurseListFk()
      },

      //查询待床患者列表
      getNoBedPatientListFk(){
        getNoBedPatientList().then(res =>{
          //alert(JSON.stringify(res.content))
          this.noBedPatientList=res.content
        })
      },

      //获取护士列表
      getNurseListFk(){
        getNurseList().then(res =>{
          //alert(JSON.stringify(res.content))
          this.nurseList=res.content
        })
      },

      //给患者添加病房与护士
      addRoomDetailToPatient(){
        if(this.addBedAndNurse.patientId == '' || this.addBedAndNurse.nurseId == ''){
          this.$notify({
                title: '提示',
                message: '请填写完整信息',
                type: 'success',
                duration: 2000
              })
        }else{
          giveBedAndNurse(this.addBedAndNurse).then(res =>{
            this.dialogFormVisible = false
            this.dialogTest = false
            this.$notify({
              title: '成功',
              message: '分配成功',
              type: 'success',
              duration: 2000
            })
            this.addBedAndNurse.nurseId=''
            this.addBedAndNurse.patientId=''
            this.addBedAndNurse.roomId=''
            this.addBedAndNurse.departmentId=''
            this.getListByPage()
          })
        }

      },

      handleFilter() {
        this.listQuery.page = 1
        this.getListByPage()
      },
      handleCreate() {
        this.tempImageList = []
        // this.$refs.imagesUpload.clearFiles()
        this.resetTemp()
        this.getDepartmentCategoryList()
        // console.log(this.userName)
        this.temp.createUserNickName = this.storeNickName
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      handleUpdate(row) {
        console.log('edit:' + row)
        this.temp = Object.assign({}, row) // copy obj
        this.temp.id = row.id
        this.dialogStatus = 'update'
        // this.getTempImageList() // 展示商品图片列表
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      handleDelete(row, index) {

        let temp = {
          id: row.id
        }

        deleteOneNewsinfoTrue(temp).then(() => {
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getListByPage()
        })

      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            addOneNewsinfo(this.temp).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: 'Created Successfully',
                type: 'success',
                duration: 2000
              })
              this.getListByPage()
            })
          }
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            updateNewsinfo(this.temp).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '编辑成功',
                type: 'success',
                duration: 2000
              })
              this.getListByPage()
            })
          }
        })
      },
      resetTemp() {
        this.temp = {
          id: '',
          title: '',
          createUserId: '',
          createUserNickName: '',
          newsContent: '',
          createTime: undefined,
          updateUserId: '',
          updateTime: undefined,
          viewNum: undefined,
          isDeleted: undefined,
          checkStatus: undefined,
          commentNum: undefined,
          categoryId: '',
        }
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);

        let imageUrl = file.response == undefined ? file.url.replace('blob:', '') : file.response.content
        // let imageUrl = ''
        let productImageData = {
          imageUrl: imageUrl
        }
        deleteSomeProductimageTrueByCondition(productImageData).then(() => {

        })

      },
      handlePictureCardPreview(file) {
        console.log(file, fileList);
        // this.dialogImageUrl = file.url;
        console.log(file.url)
        this.temp.productImages = file.url
        this.dialogVisible = true;
      },
      handleImageSuccess(res, file) {
        // console.log(res,file)
        // this.temp.headPic = URL.createObjectURL(file.raw);
        // this.temp.productImages = res.content

        let productImageData = {
          imageUrl: res.content,
          productId: this.temp.id
        }
        addOneProductimage(productImageData).then(() => {

        })
      },
      handleAvatarSuccess(res, file) {
        // console.log(res,file)
        // this.temp.headPic = URL.createObjectURL(file.raw);
        this.temp.newsImage = res.content
      },
      beforeAvatarUpload(file) {
        console.log(file)
        const fileName = file.name
        const isImage = /.(gif|jpg|jpeg|png|gif|jpg|png)$/.test(fileName);
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isImage) {
          this.$message.error('上传头像图片只能是 gif|jpg|jpeg|png|gif|jpg|png 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isImage && isLt2M;
      },
      onEditorBlur(quill) {
        // console.log('editor blur!', quill)
      },
      onEditorFocus(quill) {
        // console.log('editor focus!', quill)
      },
      onEditorReady(quill) {
        // console.log('editor ready!', quill)
      },
      onEditorChange({
        quill,
        html,
        text
      }) {
        // console.log('editor change!', quill, html, text)
        this.temp.description = html
      },
      categoryChange(){
        this.pageParam.superSearchKeyWord=""
        this.getListByPage()
      },
      updateCheckStatus(row){
        // console.log('edit:' + row)
        let temp = Object.assign({}, row) // copy obj
        temp.checkStatus = temp.checkStatus==1?2:1
        updateNewsinfo(temp).then(() => {
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: temp.checkStatus==1?'撤销成功':'发布成功',
            type: 'success',
            duration: 2000
          })
          this.getListByPage()
        })
      },
      confirmCheck(row){
        let temp = Object.assign({}, row) // copy obj
        temp.checkStatus = temp.checkStatus==0?1:0
        updateNewsinfo(temp).then(() => {
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: temp.checkStatus==0?'审核成功':'取消审核成功',
            type: 'success',
            duration: 2000
          })
          this.getListByPage()
        })
      },

      openWin(row,index){
        this.dialogTest=true
        this.getRoomListByDepartmentId(row)
      },
      //根据科室id获取病房列表
      getRoomListByDepartmentId(row){
        let tt ={
          id:row.id
        }
        getRoomListByBox(tt).then(res=>{
          // alert(JSON.stringify(res))
          this.roomList = res.content
        })
      }

    },
    mounted(){
      this.getDepartmentCategoryList()
    }




  }
</script>

<style>
  .demo-table-expand {
    font-size: 0;
  }

  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }

  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  #box {
    margin:10px auto 0;
    width:300px;
    height:210px;
    border:0px solid #000000;
  }
  div.item {
    width:100px;
    height:70px;
    margin:auto;
    float:left;
    border:0px solid lightgray;
    z-index:1;
    cursor:move;
  }
</style>
